from flask import Flask, render_template, request, session, redirect

app = Flask(__name__)

"""
1、用户登录/login
    get 
    post
2、用户退出/logout
3、主页/index
4、用户详细页面/detail
"""
app.debug = True  # 开启debug模式和django一样

app.secret_key = 'abcasdaasdasdsdas'  # 给session加的盐

USER_DICT = {  # 构造的字典
    '1': {'name': '志军', 'age': 18},
    '2': {'name': '大伟', 'age': 48},
    '3': {'name': '梅凯', 'age': 38},
}

LOGIN_USER_ACCOUNT = [  # 登录用户账号密码
    {
        'user': 'abc', 'pwd': '123'
    },
    {
        'user': 'abc1', 'pwd': '123'
    }
]


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    user = request.form.get('user')  # 获取表单中的数据
    pwd = request.form.get('pwd')
    for item in LOGIN_USER_ACCOUNT:
        if item.get('user') == user and item.get('pwd') == pwd:
            # 登录成功
            session['user_info'] = {'user': user, 'pwd': pwd}  # 把用户信息存入session中，flask中的session是直接放入cookies中
            return redirect('/index')  # 重定向到index函数路由
    else:
        return render_template('login.html', msg="登录失败")


@app.route('/index', methods=['GET'])
def index():
    user_info = session.get('user_info')
    if not user_info:
        print('登录失败')
        return redirect('/login')
    print(user_info)
    user = user_info.get('user')
    pwd = user_info.get('pwd')
    print(user, pwd)
    for item in LOGIN_USER_ACCOUNT:
        if item.get('user') == user and item.get('pwd') == pwd:
            print('登录成功', 111111111122)
            return render_template('index.html', user_dict=USER_DICT)
    return redirect('/login')


@app.route('/logout', methods=['GET'])
def logout():
    del session['user_info']
    return render_template('login.html')


@app.route('/detail', methods=['GET'])
def detail():
    user_info = session.get('user_info')
    if not user_info:
        print('登录失败')
        return redirect('/login')
    print(user_info)
    user = user_info.get('user')
    pwd = user_info.get('pwd')
    print(user, pwd)
    for item in LOGIN_USER_ACCOUNT:
        if item.get('user') == user and item.get('pwd') == pwd:
            uid = request.args.get('uid')
            if not uid:
                return redirect('/login')
            value = USER_DICT.get(uid)
            return render_template('detail.html', info=value)


if __name__ == '__main__':
    app.run()
